<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form label-width="80px">
        <el-form-item label="SPU 名称">
          <span>{{ spuInfo.spuName }}</span>
        </el-form-item>
        <el-form-item label="SKU 名称">
          <el-input
            placeholder="请输入Sku名称"
            v-model="skuInfo.skuName"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格(元)">
          <el-input
            placeholder="请输入价格"
            type="number"
            v-model="skuInfo.price"
          ></el-input>
        </el-form-item>
        <el-form-item label="重量(克)">
          <el-input
            placeholder="请输入重量"
            type="number"
            v-model="skuInfo.weight"
          ></el-input>
        </el-form-item>
        <el-form-item label="规格描述">
          <el-input
            placeholder="请输入规格描述"
            type="textarea"
            v-model="skuInfo.skuDesc"
          ></el-input>
        </el-form-item>
        <el-form-item label="平台属性">
          <el-form label-width="80px" :inline="true">
            <el-form-item
              v-for="attr in attrList"
              :key="attr.id"
              :label="attr.attrName"
            >
              <el-select placeholder="请选择" v-model="attr.attrIdValueId">
                <el-option
                  v-for="item in attr.attrValueList"
                  :key="item.id"
                  :value="`${item.attrId}:${item.id}`"
                  :label="item.valueName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-form label-width="80px" :inline="true">
            <el-form-item
              v-for="saleAttr in saleAttrList"
              :key="saleAttr.id"
              :label="saleAttr.saleAttrName"
            >
              <el-select
                placeholder="请选择"
                v-model="saleAttr.saleAttrIdValueId"
              >
                <el-option
                  v-for="item in saleAttr.spuSaleAttrValueList"
                  :key="item.id"
                  :value="`${item.baseSaleAttrId}:${item.id}`"
                  :label="item.saleAttrValueName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="图片列表">
          <el-table
            :data="imageList"
            border
            stripe
            @selection-change="imgSelectChange"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column label="图片">
              <template v-slot="{ row }">
                <img :src="row.imgUrl" width="100" alt="" />
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="imgName"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-tag type="warning" size="default" v-if="row.isDefault"
                  >默认图片</el-tag
                >

                <el-button
                  v-else
                  type="primary"
                  size="default"
                  @click="setDefaultImg(row)"
                  :disabled="!row.isSelect"
                  >设置为默认</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="save"
            >保存</el-button
          >
          <el-button size="default" @click="emit('changeShowIndex', 1)"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
  import { defineComponent } from "vue"

  export default defineComponent({
    name: "SkuInfo",
  })
</script>

<script setup lang="ts">
  import type {
    spuInfoItemType,
    spuSaleAttrListType,
    spuImageListType,
    spuImageItemType,
  } from "@/api/spu"
  import type { attrListType } from "@/api/attr"
  import type {
    skuInfoType,
    skuAttrValueListType,
    skuSaleAttrValueListType,
    skuImageListType,
  } from "@/api/sku"
  import { onMounted, ref } from "vue"
  import { reqAttrList } from "@/api/attr"
  import { reqSaleAttrListBySpuId, reqImageListBySpuId } from "@/api/spu"
  import { reqAddSku } from "@/api/sku"
  import { ElMessage } from "element-plus"
  import { storeToRefs } from "pinia"
  import useCategoryStore from "@/stores/category"
  //得到category的pinia中的store对象
  const categoryStore = useCategoryStore()

  //从pinia中拿到category的3个id,用来请求列表
  const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore)

  //接收点击进入当前组件的spuInfo
  const props = defineProps<{
    spuInfo: spuInfoItemType
  }>()

  //接收切换组件的自定义事件
  const emit = defineEmits<{
    (event: "changeShowIndex", index: number): void
  }>()

  //定义初始值接收平台属性，销售属性，图片列表
  const attrList = ref<attrListType>([])
  const saleAttrList = ref<spuSaleAttrListType>([])
  const imageList = ref<spuImageListType>([])

  //定义一个数据，用来收集被选中的图片的列表
  const selectImgList = ref<spuImageListType>([])

  //初始化发送平台属性，销售属性，图片列表请求
  onMounted(async () => {
    const promise1 = reqAttrList(
      category1Id.value as number,
      category2Id.value as number,
      category3Id.value as number
    )
    const promise2 = reqSaleAttrListBySpuId(props.spuInfo.id as number)
    const promise3 = reqImageListBySpuId(props.spuInfo.id as number)
    const result = await Promise.all([promise1, promise2, promise3])
    // console.log(result)

    //给响应式数据赋值操作
    attrList.value = result[0]
    saleAttrList.value = result[1]
    imageList.value = result[2]

    //平台属性数据请求回来之后，给每一个值添加一个attrIdValueId属性，收集当前平台属性选项的选择
    attrList.value.forEach((item) => {
      item.attrIdValueId = ""
    })

    //销售属性数据请求回来之后,给每一个值添加一个saleAttrIdValueId属性,收集当前销售属性选项的选择
    saleAttrList.value.forEach((item) => {
      item.saleAttrIdValueId = ""
    })

    //图片列表数据请求回来之后，给每一个值添加一个isSelect和isDefault属性,用来判断是否被选中以及是否为默认图片
    imageList.value.forEach((item) => {
      item.isSelect = false
      item.isDefault = false
    })
  })

  //初始化一个数据,用来收集参数
  const skuInfo = ref<skuInfoType>({
    spuId: props.spuInfo.id as number,
    tmId: props.spuInfo.tmId as number,
    category3Id: props.spuInfo.category3Id,

    price: 0,
    skuName: "",
    skuDesc: "",
    weight: "",
    skuDefaultImg: "",
    isSale: 1, //固定是上架状态
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  })

  //表格的多选框发生改变后的事件回调函数
  const imgSelectChange = (selectList: spuImageListType) => {
    //遍历所有的图片，把每一项的isSelect属性都变成false
    //因为“设置为默认”按钮的禁用条件就是当isSelect为false的时候
    imageList.value.forEach((item) => {
      item.isSelect = false
    })
    //然后再遍历所有被勾选的图片，把每一项的isSelect变为true，这样一来被勾选的图片就可以点击“设置为默认”按钮，而未被勾选的图片不能点击“设置为默认”按钮（排他思想）
    selectList.forEach((item) => {
      item.isSelect = true
    })

    //参数就是:一个收集所有被选中的表格中的row数据组成的数组,直接将其赋值给上面定义的被选中的图片列表进行收集
    selectImgList.value = selectList
  }

  //点击设置默认图片的事件回调函数
  const setDefaultImg = (row: spuImageItemType) => {
    //使用排他,把所有图片的isDefault设置为false
    imageList.value.forEach((item) => {
      item.isDefault = false
    })
    //再把当前选中的那一项的isDefault设置为true
    row.isDefault = true

    //把默认图片地址设置给skuInfo中收集
    skuInfo.value.skuDefaultImg = row.imgUrl
  }

  //点击保存按钮的事件回调函数
  const save = async () => {
    //整理参数1--平台属性
    //遍历attrList，判断哪一项有attrIdValueId属性，如果有，则代表这一项是被选中的
    attrList.value.forEach((item) => {
      if (item.attrIdValueId) {
        const [attrId, valueId] = item.attrIdValueId.split(":")
        ;(skuInfo.value.skuAttrValueList as skuAttrValueListType).push({
          attrId: +attrId,
          valueId: +valueId,
        })
      }
    })

    //整理参数2--销售属性
    //遍历saleAttrList，判断哪一项有saleAttrIdValueId属性，如果有，则代表这一项是被选中的
    saleAttrList.value.forEach((item) => {
      if (item.saleAttrIdValueId) {
        const [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":")
        ;(skuInfo.value.skuSaleAttrValueList as skuSaleAttrValueListType).push({
          saleAttrId: +saleAttrId,
          saleAttrValueId: +saleAttrValueId,
        })
      }
    })

    //整理参数3--图片列表
    selectImgList.value.forEach((item) => {
      //因为是对已被选好的图片进行遍历，所以直接插入到skuInfo中的skuImageList里面
      ;(skuInfo.value.skuImageList as skuImageListType).push({
        imgName: item.imgName, //图片名称
        imgUrl: item.imgUrl, //图片地址
        spuImgId: item.id as number, //在spu中的id
        isDefault: "0", //是否是当前的默认图片
      })
    })

    //参数整理完毕直接发送请求
    await reqAddSku(skuInfo.value)
    //提示信息
    ElMessage.success("添加Sku成功！")
    //切换至列表展示页面
    emit("changeShowIndex", 1)
  }
</script>

<style scoped lang="scss"></style>
